package com.seestech.sell.common.config.filter;

import com.seestech.sell.common.utils.Constants;
import com.seestech.sell.domain.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/14.
 * @description  过滤器  当session中用户失效时  跳转至登录页面
 */
public class AdminUserFilter implements Filter {
    private static Logger logger = LoggerFactory.getLogger(AdminUserFilter.class);

    private static List<String> excludeList = new ArrayList<>();

    //静态块   初始化  不需要过滤的路径
    static {
        excludeList.add("/user");
        excludeList.add("/company");
        excludeList.add("/brand");
        excludeList.add("/order");
        excludeList.add("/recorder");
        excludeList.add("/refund");
        excludeList.add("/stock");
        excludeList.add("/shelf");
        excludeList.add("/grid");
        excludeList.add("/goods");
        excludeList.add("/area");
        excludeList.add("/cloudDisk");
        excludeList.add("/monitor");
        excludeList.add("/permission");
        excludeList.add("/release");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //do something
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getServletPath();

        //遍历需要过滤的路径  是否符合
        for (String item : excludeList){
            if(url.startsWith(item)){
                logger.debug("过滤器====>检测session中的用户是否失效======>");
                User user = (User) request.getSession().getAttribute(Constants.Regular.onlineUser);
                if(user != null){
                    break;
                }else{
                    logger.info("当前session中用户已经失效=====>跳转至登录页面");
                    //跳转登录页面
                    //request.getRequestDispatcher("/login.html").forward(request_local.get(), response_local.get());
                    //post请求的时候返回js脚本
                    if(request.getMethod().equalsIgnoreCase("POST")){
                        response.getWriter().write("<script type='text/javascript'>layer.msg('用户登录已经失效，即将前往登录页面', {icon:5, time:2000}, function(){top.location.href='"+request.getContextPath()+"/login.html'})</script>");
                    }else
                        response.sendRedirect(request.getContextPath()+"/login.html");
                    return;
                }
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        //do something
    }

}
